package com.fast.pojo.dto;

import com.fast.pojo.entity.SysUserDo;
import com.fast.pojo.vo.UserRouteVO;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.pojo.dto.SecurityUserDTo
 * @description: 封装数据库中查询的用户数据信息
 * @since 2024/6/23 16:20
 */
@Getter
@Setter
public class SecurityUserDTO implements UserDetails {

    private static final long serialVersionUID = 1L;

    /**
     * 用户实体
     */
    private SysUserDo sysUserDo;

    /**
     * 后端有权限的url列表
     * 用于判断后端是否授权，前端的细粒度控制
     */
    private Set<String> backAuthorities;

    /**
     * 封装前端的动态路由，前端根据这些动态路由:
     * 1.计算动态路由--tabs
     * 2.计算菜单
     */
    private List<UserRouteVO> userRoutes;

    /**
     * security会调用这个方法来判断当前用户拥有的权限
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtils.isEmpty(backAuthorities)) {
            return Collections.emptyList();
        }
        return backAuthorities.stream().filter(StringUtils::hasText).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return sysUserDo.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUserDo.getUserName();
    }

    /**
     * 是不是非过期
     *
     * @return 没过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 是不是非上锁
     *
     * @return 没上锁
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }


    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return sysUserDo.getDisabledFlag() == 0;
    }
}
